package com.imc.api.attence.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.imc.api.attence.pojo.Leave;
import com.imc.api.attence.service.LeaveService;
import com.imc.api.templmess.pojo.*;
import com.imc.api.templmess.service.TemplateService;
import com.imc.api.templmess.service.http.ITempMessService;
import com.imc.api.templmess.utils.TemplateData;
import com.imc.core.annotation.Logs;
import com.imc.core.config.feign.MyPageImpl;
import com.imc.core.utils.MysqlUtil;
import com.imc.platform.base.leave.pojo.MakeMissLesson;
import com.imc.platform.base.user.pojo.User;
import com.twp.common.component.process.exception.combo.IComboExecptionForTFunc;
import com.twp.common.tuple.ResultDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.imc.api.templmess.utils.WeiXinEnum.appsecret;

/*
 * 类描述：请假管理
 * 开发者：tanweiping
 * 创建日期：2018/10/28 20:36
 */
@Slf4j
@RestController
@RequestMapping("/api/leave")
public class LeaveController {

    @Autowired
    IComboExecptionForTFunc iComboExecptionForTFunc;

    @Autowired
    LeaveService leaveService;//请假服务类

    @Autowired
    MysqlUtil mysqlUtil;//数据库操作类

    @Autowired
    NotifyPropertyConfig notifyPropertyConfig;

    @Autowired
    TemplateService templateService;

    private static final String page="pages/mine/exchange/index?messageTuple=1&leaveDetailId=";
    /**
     * QY 2018/9/3 8:01
     * 方法描述：传参对象
     **/
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class ReqTuple {
        Map <String, String> parmsMap;
        MakeMissLesson makeMissLesson;
    }

    /*
     * YT  2018/10/28 20:36
     * 方法描述：获取课程列表
     */
    @GetMapping("/getLessionList")
    ResultDTO getLessionList(
            Principal principal,
            @RequestParam(defaultValue = "forLeave") String forW,
            @RequestParam(defaultValue = "") String child,
            @RequestParam(defaultValue = "student") String option) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    t.setData(
                            option.equals("student")
                                    ?
                                    leaveService.getLessionListForStu(forW, principal.getName(),child)
                                    :
                                    leaveService.getLessionListForTeach(forW, principal.getName())
                    );
                },
                (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("获取课程失败");
                }
        );
    }

//    @GetMapping("/getLessionListForTeach")
//    ResultDTO getLessionListForTeach(Principal principal){
//        return iComboExecptionForTFunc.executeFlow(
//                ResultDTO.builder().build(),
//                t->{
//                    t.setData(leaveService.getLessionListForTeach(principal.getName()));
//                },
//                (e,t)->{
//                    e.printStackTrace();
//                    t.setIsSuccess(false);
//                    t.setMessage("获取课程失败");
//                }
//        );
//    }

    /*
     * tanweiping  2018/9/25 06:40
     * 方法描述：发起请假
     */
    @Logs
    @PostMapping("")
    ResultDTO postLeave(Principal principal, @RequestBody Leave leave) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    try {
                        leaveService.postleave(principal, leave);
                        t.setMessage("发起请假成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                        t.setMessage(e.getMessage());
                        t.setIsSuccess(false);
                    }
                },
                (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("发起请假失败");
                }
        );
    }

    /*
     * tanweiping  2018/9/25 06:44
     * 方法描述：请假流程操作，允许，不允许
     */
    @PutMapping("/audit/{status}")
    ResultDTO audit(Principal principal, @RequestBody List <String> ids, @PathVariable String status) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    leaveService.audit(principal, ids, status);
                },
                (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("审核失败");
                }
        );
    }

    /*
     * tanweiping  2018/9/25 06:58
     * 方法描述：查看请假记录
     */
    @GetMapping("")
    ResultDTO getLeaveList(
            Principal principal,
            @RequestParam(defaultValue = "permit") String option,
            @PageableDefault(
                    sort = {"updateTime"}, direction = Sort.Direction.DESC
            ) Pageable pageable) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    t.setData(leaveService.getLeaveList(principal, option, pageable));
                },
                (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查看请假记录失败");
                }
        );
    }

    @GetMapping("/pageable")
    ResultDTO getLeaveListByPageAble(
            Principal principal,
            @RequestParam(defaultValue = "permit") String option,
            @PageableDefault(
                    sort = {"updateTime"}, direction = Sort.Direction.DESC
            ) Pageable pageable) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    t.setData(leaveService.getLeaveListByPageable(principal, option, pageable));
                },
                (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("查看请假记录失败");
                }
        );
    }

    /*
     *删除请假
     */
    @DeleteMapping("/{id}")
    ResultDTO deleteLeaveById(@PathVariable String id) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    leaveService.deleteLeavById(id);
                },
                (e, t) -> {
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("删除请假失败");
                }
        );
    }

    @GetMapping("/addMakeMissLesson")
    @ResponseBody
    ResultDTO addMakeMissLesson(@RequestParam String leaveDetId,@RequestParam String formId, HttpServletRequest request){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    Map<String,Object>resMap=new HashMap<>();
                    User user=(User) request.getSession().getAttribute("currentUser");
                    List<MakeMissLesson>makeMissLessonsList=leaveService.queryMakeList(leaveDetId);
                    if(makeMissLessonsList.size()>0){
                        t.setIsSuccess(false);
                        t.setMessage("已存在新增补课请求，请等待补课通知");
                    }else {
                        MakeMissLesson makeMissLesson=MakeMissLesson.builder()
                                .leaveDetId(Integer.parseInt(leaveDetId))
                                .createTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                                .auditorId(user.getId())
                                .formId(formId)
                                .build();
                        //新增补课申请
                        leaveService.addMakeMissLesson(makeMissLesson);
                        resMap.put("id",makeMissLesson.getId());
                        //获取所属学校信息
                        Map<String,Object>orgMap=leaveService.queryLessonOrgName(makeMissLesson.getLeaveDetId());
                        //封装消息模板
                        Map<String, TemplateData>param=new HashMap<>();
                        param.put("keyword1", new TemplateData(user.getTrueName(), "#696969"));
                        param.put("keyword2", new TemplateData(user.getTel(), "#696969"));
                        param.put("keyword3", new TemplateData(orgMap.get("orgName").toString(), "#696969"));
                        param.put("keyword4", new TemplateData("您有一个学生申请补课，请点击查看", "#696969"));
                        param.put("keyword5", new TemplateData(makeMissLesson.getCreateTime(), "#696969"));
                        //根据学校orgId获取所有分校校长的集合
                        List<Map<String,Object>>getOpenIdList=leaveService.queryMasterList(Integer.parseInt(orgMap.get("id").toString()));
                        Token token=Token.builder()
                                .appid(notifyPropertyConfig.getAppid())
                                .secret(notifyPropertyConfig.getAppsecret())
                                .grant_type("client_credential")
                                .build();

                        Map<String,Object>miniprogram=new HashMap<>();
                        miniprogram.put("appid",notifyPropertyConfig.getAppid());
                        miniprogram.put("pagepath",page+makeMissLesson.getLeaveDetId());
                        TempMall tempMall=TempMall.builder()
                                .access_token(templateService.getAccessToken(token))
                                .mp_template_msg(Mp_template_msg.builder()
                                        .appid(notifyPropertyConfig.getPubliceId())
                                        .template_id(notifyPropertyConfig.getPubliceAddress().getMissLessonTempletId())
                                        .url("")
                                        .miniprogram(miniprogram)
                                        .data(param)
                                        .build())
                                .build();
                        for(Map map:getOpenIdList){
                            log.info("登陆号码:"+user.getLoginName()+",获取到的校长openid:"+map.get("openId"));
                           if(!map.get("openId").equals("") && map.get("openId") != null ){
                               tempMall.setTouser(map.get("openId").toString());
                               //发送给审核人需要发送公众号
                               log.info("发送消息模板数据:"+tempMall);
                               JSONObject result= templateService.messSend(tempMall);
                               log.info("发送消息模板返回数据:"+result.toString());
                               if(result.getString("errcode").equals("43004")){
                                     log.info("trueName:"+map.get("trueName")+",loginName:"+map.get("loginName"));
                               }
                           }
                        }
                        t.setData(resMap);
                        t.setMessage("创建补课流程成功");
                    }
                },
                (e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("创建补课流程失败");
                }
        );
    }

    @GetMapping("/sendMessage")
    @ResponseBody
    ResultDTO sendMessage(){
        return iComboExecptionForTFunc.executeFlow(
            ResultDTO.builder().build(),
            t->{
                Map<String, TemplateData>param=new HashMap<>();
                param.put("keyword1", new TemplateData("小红", "#696969"));
                param.put("keyword2", new TemplateData("15261815812", "#696969"));
                param.put("keyword3", new TemplateData("胜太西路", "#696969"));
                param.put("keyword4", new TemplateData("您有一个学生申请补课，请点击查看", "#696969"));
                param.put("keyword5", new TemplateData(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), "#696969"));
                Token token=Token.builder()
                        .appid(notifyPropertyConfig.getAppid())
                        .secret(notifyPropertyConfig.getAppsecret())
                        .grant_type("client_credential")
                        .build();

                String str= templateService.getAccessToken(token);
                log.info(str);
                Map<String,Object>miniprogram=new HashMap<>();
                miniprogram.put("appid",notifyPropertyConfig.getPubliceId());
                miniprogram.put("pagepath",page+"613");
                TempMall tempMall=TempMall.builder()
                        .access_token(templateService.getAccessToken(token))
                        .touser("ooWLD5Alzc2rkgNBpKM-umAGpkrk")
                        .mp_template_msg(Mp_template_msg.builder()
                                .appid(notifyPropertyConfig.getAppid())
                                .template_id(notifyPropertyConfig.getPubliceAddress().getMissLessonTempletId())
                                .url("")
                                .miniprogram(miniprogram)
                                .data(param)
                                .build())
                        .build();
                JSONObject result= templateService.messSend(tempMall);
                 log.info(result.toString());
//                //根据学校orgId获取所有分校校长的集合
//                List<String>getOpenIdList=leaveService.queryMasterList(Integer.parseInt(orgMap.get("id").toString()));
                //调取微信接口发送消息
//                WX_TemplateMsgUtil.getInstance().sendWechatMsgToUser(page+"613", "1546850785371", "ooWLD5O2QUIBzYxuYFPeIlcDTEtc", templetId, "", "#000000", packJsonmsg(param), appid, appsecret);
            }   ,(e,t)->{
                    e.printStackTrace();
                    t.setIsSuccess(false);
                    t.setMessage("消息发送失败");
                }
        );
    }

    @PostMapping("/updateMakeMissLesson")
    @ResponseBody
    ResultDTO updateMakeMissLesson(@RequestParam int id, @RequestBody Map<String,Object> result,@RequestParam String formId, HttpServletRequest request){
         return iComboExecptionForTFunc.executeFlow(
                 ResultDTO.builder().build(),
                 t->{
                     User user=(User) request.getSession().getAttribute("currentUser");
                     MakeMissLesson makeMissLesson=MakeMissLesson.builder()
                             .id(id)
                             .result(result.get("result").toString())
                             .updateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                             .auditorId(user.getId())
                             .build();
                     Map<String,Object>orgMap=leaveService.queryLessonOrgNameByMessId(makeMissLesson.getId());
                     if(!user.getDuty().equals("branch")){
                         t.setIsSuccess(false);
                         t.setMessage("您没有操作权限批准补课");
                     }
                     Map<String,Object>stateMap=leaveService.queryMakeMissLessonState(id);
                     if(!stateMap.get("state").equals("1")){
                         leaveService.updateMakeMissLesson(makeMissLesson);
                         Map<String, TemplateData>param=new HashMap<>();
                         param.put("keyword1", new TemplateData(user.getTrueName(), "#696969"));
                         param.put("keyword2", new TemplateData(user.getTel(), "#696969"));
                         param.put("keyword3", new TemplateData(orgMap.get("orgName").toString(), "#696969"));
                         param.put("keyword4", new TemplateData("补课申请处理完毕，请点击查看", "#696969"));
                         param.put("keyword5", new TemplateData(makeMissLesson.getCreateTime(), "#696969"));
                         Token token=Token.builder()
                                 .appid(notifyPropertyConfig.getAppid())
                                 .secret(notifyPropertyConfig.getAppsecret())
                                 .grant_type("client_credential")
                                 .build();
                         TempMall tempMall=TempMall.builder()
                                 .access_token(templateService.getAccessToken(token))
                                 .touser(leaveService.queryProposer(Integer.parseInt(stateMap.get("leaveDetId").toString())))
                                 .weapp_template_msg(Weapp_template_msg.builder()
                                         .template_id(notifyPropertyConfig.getAppAddress().getMissLessonTempletId())
                                         .page(page+stateMap.get("leaveDetId").toString())
                                         .form_id(leaveService.queryMissLessonFormId(Integer.parseInt(stateMap.get("leaveDetId").toString())))
                                         .data(param)
                                         .emphasis_keyword("")
                                         .build())
                                 .build();
                         log.info("发送消息模板数据:"+tempMall);
                         JSONObject res= templateService.messSend(tempMall);
                         log.info("发送消息模板返回数据:"+res.toString());
                         t.setMessage("修改补课流程成功");
                     }else {
                         t.setIsSuccess(false);
                         t.setMessage("改补课申请已被其他校长同意");
                     }
                 },
                 (e,t)->{
                     e.printStackTrace();
                     t.setIsSuccess(false);
                     t.setMessage("修改补课流程失败");
                 }
         );
    }

    @GetMapping("/showMakeMissLesson")
    @ResponseBody
    ResultDTO showMakeMissLesson(@RequestParam int id){
       return iComboExecptionForTFunc.executeFlow(
               ResultDTO.builder().build(),
               t->{
                   t.setData(leaveService.showMakeMissLesson(id));
                   t.setMessage("查询成功");
               },(e,t)->{
                   e.printStackTrace();
                   t.setIsSuccess(false);
                   t.setMessage("展示模板详情失败");
               }
       );
    }

    @GetMapping("/getMissLessonList")
    @ResponseBody
    ResultDTO getMissLessonList(Principal principal,@PageableDefault Pageable pageable){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    PageInfo<Map<String,Object>> result=leaveService.queryMissLessonList(pageable,principal.getName());
                    t.setData(new MyPageImpl<>(result.getList(), result.isIsLastPage()));
                    t.setMessage("查询成功");
                },(e,t)->{

                }
        );
    }

}